package com.zhz.confirm;

import com.rabbitmq.client.*;
import com.zhz.utils.RabbitConstant;
import com.zhz.utils.RabbitUtils;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author ：zhz
 * @date ：Created in 2021/02/03
 * @version: V1.0
 * @slogan: 天下风云出我辈，一入代码岁月催
 * @description: 生产者=>不需要关闭，因为要监听
 **/
public class WeatherBureau {
    public static void main(String[] args) throws IOException {
        Map<String, String> area = new LinkedHashMap<>();
        area.put("china.hunan.changsha.20201127", "中国湖南长沙20201127天气数据");
        area.put("china.hubei.wuhan.20201127", "中国湖北武汉20201127天气数据");
        area.put("china.hunan.zhuzhou.20201127", "中国湖南株洲20201127天气数据");
        area.put("us.cal.lsj.20201127", "美国加州洛杉矶20201127天气数据");

        area.put("china.hebei.shijiazhuang.20201128", "中国河北石家庄20201128天气数据");
        area.put("china.hubei.wuhan.20201128", "中国湖北武汉20201128天气数据");
        area.put("china.henan.zhengzhou.20201128", "中国河南郑州20201128天气数据");
        area.put("us.cal.lsj.20201128", "美国加州洛杉矶20201128天气数据");
        Connection connection = RabbitUtils.getConnection();
        Channel channel = connection.createChannel();
        //开启confirm监听模式
        channel.confirmSelect();
        channel.addConfirmListener(new ConfirmListener() {
            @Override
            public void handleAck(long l, boolean b) throws IOException {
                //第二个参数代表接收的数据是否为批量接收,一般不用
                System.out.println("消息已被Broker接收，Tag="+l);
            }

            @Override
            public void handleNack(long l, boolean b) throws IOException {
                System.out.println("消息已被Broker拒收,Tag:" + l);
            }
        });
        channel.addReturnListener(new ReturnCallback() {
            @Override
            public void handle(Return aReturn) {
                System.err.println("===========================");
                System.err.println("Return编码：" + aReturn.getReplyCode() + "-Return描述:" + aReturn.getReplyText());
                System.err.println("交换机:" + aReturn.getExchange() + "-路由key:" + aReturn.getRoutingKey() );
                System.err.println("Return主题：" + new String(aReturn.getBody()));
                System.err.println("===========================");
            }
        });
        Iterator<Map.Entry<String, String>> iterator = area.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> map = iterator.next();
            channel.basicPublish(RabbitConstant.EXCHANGE_WEATHER_TOPIC,map.getKey(),true,null,map.getValue().getBytes());
        }
    }
}
